#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re
from typing import List, Dict

def parse_diff(diff_text: str) -> List[Dict]:
    """
    解析 unified diff 格式的文本，返回每个 hunk 的详细修改内容。
    返回结构:
    [
        {
            "hunk_header": "@@ -1,3 +1,4 @@",
            "changes": [
                {"type": "context", "content": " unchanged line\n unchanged line2\n"},
                {"type": "remove", "content": " old line"},
                {"type": "add", "content": " new line"},
                {"type": "context", "content": " unchanged line3\n"}
            ]
        },
        ...
    ]
    """
    hunks = []
    current_hunk = None

    if not diff_text:
        return hunks

    hunk_pattern = re.compile(r"^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@")

    # 保留原始换行符，避免在后续处理时丢失回车信息
    for line in diff_text.splitlines(keepends=True):
        if hunk_pattern.match(line):
            if current_hunk:
                hunks.append(current_hunk)
            current_hunk = {"hunk_header": line.rstrip('\n\r'), "changes": []}
            continue

        if line.startswith("--- ") or line.startswith("+++ "):
            continue

        if current_hunk is None:
            continue

        # 根据符号解析行类型
        if line.startswith("+") and not line.startswith("+++"):
            if (current_hunk["changes"] and 
                current_hunk["changes"][-1]["type"] == "add"):
                current_hunk["changes"][-1]["content"] += line[1:]
            else:
                current_hunk["changes"].append({"type": "add", "content": line[1:]})
        elif line.startswith("-") and not line.startswith("---"):
            if (current_hunk["changes"] and 
                current_hunk["changes"][-1]["type"] == "remove"):
                current_hunk["changes"][-1]["content"] += line[1:]
            else:
                current_hunk["changes"].append({"type": "remove", "content": line[1:]})
        else:
            if (current_hunk["changes"] and 
                current_hunk["changes"][-1]["type"] == "context"):
                current_hunk["changes"][-1]["content"] += line
            else:
                current_hunk["changes"].append({"type": "context", "content": line})

    if current_hunk:
        hunks.append(current_hunk)

    return hunks

def reconstruct_hunk_diff(hunk: Dict) -> str:
    """
    根据单个 hunk 数据，重建它对应的 unified diff 片段字符串，
    包含hunk header行 + 每个 change 行的标记和内容。
    """
    lines = [hunk['hunk_header'] + '\n']

    for change in hunk['changes']:
        prefix = {
            "context": " ",
            "add": "+",
            "remove": "-"
        }[change['type']]

        content = change['content']
        # 逐行加前缀，保留原始换行符
        for seg in content.splitlines(keepends=True):
            # 即使是空行也应当保留一行（seg 可能为 '\n'）
            lines.append(prefix + seg)

    return ''.join(lines) 